import { _decorator, Component, EventTouch, Input, input, Node, UIOpacity, UITransform, Vec2 } from 'cc';
import { AudioManager, Core } from './Core/Core';
import { EEvent } from './Config/Enum';
const { ccclass, property } = _decorator;

@ccclass('JoyStickManager')
export class JoyStickManager extends Component {

    input: Vec2 = new Vec2(0, 0) //给外界访问

    private body: Node
    private stick: Node
    private defaultPos: Vec2
    private radius: number

/*************  ✨ Codeium Command ⭐  *************/
    /**
     * Lifecycle method, called when the node is loaded.
     * Get the UI nodes, set the default position of the stick and its radius.
     * Register the event listeners for touch start, move and end.
     */
/******  df1ada82-a747-437b-9f18-1dbd202279dc  *******/
    onLoad() {
        this.node.getComponent(UIOpacity).opacity = 0
        this.body = this.node.getChildByName('Body')
        this.stick = this.body.getChildByName('Stick')
        this.defaultPos = new Vec2(this.body.position.x, this.body.position.y)
        this.radius = this.body.getComponent(UITransform).contentSize.x / 2



    }

    onDestroy(): void {

        
    }

    protected onEnable(): void {
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
        
    }

    protected onDisable(): void {
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this)
        input.off(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
        input.off(Input.EventType.TOUCH_END, this.onTouchEnd, this)
        
    }

    
    start() {

    }

    update(deltaTime: number) {
        
    }

    onTouchStart(e: EventTouch) {
        const touchPos = e.getUILocation()
        //console.log("touchPos", touchPos)
        this.body.setPosition(touchPos.x, touchPos.y)
    }

    onTouchMove(e: EventTouch) {
        this.node.getComponent(UIOpacity).opacity = 255
        const touchPos = e.getUILocation()
        const stickPos = new Vec2(touchPos.x - this.body.position.x, touchPos.y - this.body.position.y)
        if (stickPos.length() > this.radius) {
            stickPos.multiplyScalar(this.radius / stickPos.length())
          }
          this.stick.setPosition(stickPos.x, stickPos.y)
      
          this.input = stickPos.clone().normalize()
          // Core.Instance.event.emit(EEvent.PLAYER_MOVE,this.input)
          //console.log("this.input", this.input) 
      }

    onTouchEnd(){
        // AudioManager.Instance.playSound('paopao', 0.5)

        

        this.body.setPosition(this.defaultPos.x, this.defaultPos.y)
        this.stick.setPosition(0, 0)
        this.input = Vec2.ZERO
        this.node.getComponent(UIOpacity).opacity = 0
    }
}


